package com.scut.online_black_market.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.scut.online_black_market.entity.Personal;
import com.scut.online_black_market.mapper.PersonalMapper;
import com.scut.online_black_market.service.AliPayService;
import com.scut.online_black_market.utility.AliPayClientUtil;
import com.scut.online_black_market.utility.JwtUtil;
import com.scut.online_black_market.utility.RedisUtil;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

/**
 * create by yellowBroke on 2020年11月28日 14点16分
 * 支付宝接口
 */
@Service
public class AliPayServiceImpl implements AliPayService {

    @Resource
    private HttpServletRequest httpServletRequest;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private PersonalMapper personalMapper;

    @Value("${sdk.alipay.alipay-public-key}")
    private String ALIPAY_PUBLIC_KEY;

    @Override
    public String recharge(float money) throws AlipayApiException {
        String studentNumber = jwtUtil.extractStudentNumber(httpServletRequest);
        //获得不重复的订单号
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-", "");
        redisUtil.set(uuid, studentNumber);
        return AliPayClientUtil.getInstance().createTrade(money, uuid);
    }

    @Override
    public String validateAliPay(Map<String, String> conversionParams) {


            //签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
        boolean signVerified = false;

        try {
                //调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(conversionParams, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2");

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //对验签进行处理
        if (signVerified) {
            //验签通过
            //获取需要保存的数据
            String appId=conversionParams.get("app_id");//支付宝分配给开发者的应用Id
            String notifyTime=conversionParams.get("notify_time");//通知时间:yyyy-MM-dd HH:mm:ss
            String gmtCreate=conversionParams.get("gmt_create");//交易创建时间:yyyy-MM-dd HH:mm:ss
            String gmtPayment=conversionParams.get("gmt_payment");//交易付款时间
            String gmtRefund=conversionParams.get("gmt_refund");//交易退款时间
            String gmtClose=conversionParams.get("gmt_close");//交易结束时间
            String tradeNo=conversionParams.get("trade_no");//支付宝的交易号
            String outTradeNo = conversionParams.get("out_trade_no");//获取商户之前传给支付宝的订单号（商户系统的唯一订单号）
            String outBizNo=conversionParams.get("out_biz_no");//商户业务号(商户业务ID，主要是退款通知中返回退款申请的流水号)
            String buyerLogonId=conversionParams.get("buyer_logon_id");//买家支付宝账号
            String sellerId=conversionParams.get("seller_id");//卖家支付宝用户号
            String sellerEmail=conversionParams.get("seller_email");//卖家支付宝账号
            float totalAmount= Float.parseFloat(conversionParams.get("total_amount")) ;//订单金额:本次交易支付的订单金额，单位为人民币（元）
            String receiptAmount=conversionParams.get("receipt_amount");//实收金额:商家在交易中实际收到的款项，单位为元
            String invoiceAmount=conversionParams.get("invoice_amount");//开票金额:用户在交易中支付的可开发票的金额
            String buyerPayAmount=conversionParams.get("buyer_pay_amount");//付款金额:用户在交易中支付的金额
            String tradeStatus = conversionParams.get("trade_status");// 获取交易状态


            String studentNumber = (String) redisUtil.get(outTradeNo);

            Personal personal = personalMapper.selectById(studentNumber);
            personal.setBalance(personal.getBalance() + totalAmount);
            int returnResult =  personalMapper.updateById(personal);

//           //支付宝官方建议校验的值（out_trade_no、total_amount、sellerId、app_id）
//           AlipaymentOrder alipaymentOrder=this.selectByOutTradeNo(outTradeNo);
//
//            if(alipaymentOrder!=null&&totalAmount.equals(alipaymentOrder.getTotalAmount().toString())&&AlipayConfig.APPID.equals(appId)){
//                //修改数据库支付宝订单表(因为要保存每次支付宝返回的信息到数据库里，以便以后查证)
//                alipaymentOrder.setNotifyTime(dateFormat(notifyTime));
//                alipaymentOrder.setGmtCreate(dateFormat(gmtCreate));
//                alipaymentOrder.setGmtPayment(dateFormat(gmtPayment));
//                alipaymentOrder.setGmtRefund(dateFormat(gmtRefund));
//                alipaymentOrder.setGmtClose(dateFormat(gmtClose));
//                alipaymentOrder.setTradeNo(tradeNo);
//                alipaymentOrder.setOutBizNo(outBizNo);
//                alipaymentOrder.setBuyerLogonId(buyerLogonId);
//                alipaymentOrder.setSellerId(sellerId);
//                alipaymentOrder.setSellerEmail(sellerEmail);
//                alipaymentOrder.setTotalAmount(Double.parseDouble(totalAmount));
//                alipaymentOrder.setReceiptAmount(Double.parseDouble(receiptAmount));
//                alipaymentOrder.setInvoiceAmount(Double.parseDouble(invoiceAmount));
//                alipaymentOrder.setBuyerPayAmount(Double.parseDouble(buyerPayAmount));
//                switch (tradeStatus) // 判断交易结果
//                {
//                    case "TRADE_FINISHED": // 交易结束并不可退款
//                        break;
//                    case "TRADE_SUCCESS": // 交易支付成功
//                        break;
//                    case "TRADE_CLOSED": // 未付款交易超时关闭或支付完成后全额退款
//                        break;
//                    case "WAIT_BUYER_PAY": // 交易创建并等待买家付款
//                        break;
//                    default:
//                        break;
//                }
//                int returnResult=this.updateByPrimaryKey(alipaymentOrder);    //更新交易表中状态

            if(tradeStatus.equals("TRADE_SUCCESS")) {    //只处理支付成功的订单: 修改交易表状态,支付成功

                if(returnResult == 1){
                    return "success";
                }else{
                    return "fail";
                }
            }else{
                return "fail";
            }

        }else{
            return"fail";
        }

//        } else {  //验签不通过
//            log.info("==================验签不通过 ！");
//            return "fail";
//        }

        }
}
